/*
 * @title: 用户权限控制
 * @author: andy.ten@tom.com & xukaixing@hotmail.com
 * @Date: 2022-03-25 19:49:48
 * @LastEditors: andy.ten@tom.com
 * @LastEditTime: 2022-04-03 21:37:23
 * @version: 1.0.4
 * @copyright: copyright (c) 2022 andyten
 *  node: you can not copy and/or use and/or modify this program free,
 *  please reserve the segment above.Please mail me if you have any question.
 */
import { constantRoutes, resetRouter } from '@/router/routers';
import config from '@/store/config';

const state = {
  routes: [],
  sidebarRoutes: [],
  mainAppRoutes: [],
  breadcrumbRoutes: []
};

const mutations = {
  [config.SET_SIDEBAR_ROUTES]: (state, sidebarRoutes) => {
    // state.routes = constantRoutes.concat(sidebarRoutes);
    // 首页路由
    const homeChild = constantRoutes.find((item) => {
      if (item.path === '/')
        return item;
    });

    // 设置带首页的路由变量
    state.mainAppRoutes.push(...sidebarRoutes);
    state.mainAppRoutes.splice(0, 0, homeChild.children[0]);

    // 添加路由
    homeChild.children.push(...sidebarRoutes);

    // 设置左边栏路由
    if (!homeChild.children[0].hidden)
      sidebarRoutes.splice(0, 0, homeChild.children[0]);

    sidebarRoutes.push({ path: '*', redirect: '/404', hidden: true });
    state.sidebarRoutes = sidebarRoutes;

    constantRoutes.push({ path: '*', redirect: '/404', hidden: true });
    state.routes = constantRoutes;
    resetRouter();
  },
  [config.SET_BREADCRUMB_ROUTES]: (state, breadcrumbRoute) => {
    state.breadcrumbRoutes.splice(0, state.breadcrumbRoutes.length);
    state.breadcrumbRoutes.push(...breadcrumbRoute);
  }
};

const actions = {
  setSidebarRoutes({ commit }, sidebarRoutes) {
    commit(config.SET_SIDEBAR_ROUTES, sidebarRoutes);
  },
  setBreadcrumbRoutes({ commit }, breadcrumbRoutes) {
    commit(config.SET_BREADCRUMB_ROUTES, breadcrumbRoutes);
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
